/*=============================================================================

  Library: HMPBundleFrame

  Copyright (c) German Cancer Research Center,
    Division of Medical and Biological Informatics

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

=============================================================================*/

#include "Services_p.h"

#include <QStringListIterator>
#include <QMutexLocker>
#include <QBuffer>

#include <algorithm>

#include "ServiceFactory.h"
#include "BundleConstants.h"
#include "BundleFrameworkContext_p.h"
#include "ServiceException.h"
#include "ServiceRegistration_p.h"
#include "LDAPExpr_p.h"

//----------------------------------------------------------------------------
struct ServiceRegistrationComparator
{
  bool operator()(const IServiceRegistration& a, const IServiceRegistration& b) const
  {
    return a < b;
  }
};

//----------------------------------------------------------------------------
Dictionary Services::createServiceProperties(const Dictionary& in,
                                                       const QStringList& classes,
                                                       long sid)
{
  static qlonglong nextServiceID = 1;
  Dictionary props = in;

  if (!classes.isEmpty())
  {
    props.insert(BundleConstants::OBJECTCLASS, classes);
  }

  props.insert(BundleConstants::SERVICE_ID, sid != -1 ? sid : nextServiceID++);

  return props;
}

//----------------------------------------------------------------------------
Services::Services(BundleFrameworkContext* fwCtx)
  : mutex(), framework(fwCtx)
{

}

//----------------------------------------------------------------------------
Services::~Services()
{
  clear();
}

//----------------------------------------------------------------------------
void Services::clear()
{
  services.clear();
  classServices.clear();
  framework = 0;
}

//----------------------------------------------------------------------------
IServiceRegistration Services::registerService(BundlePrivate* plugin,
                             const QStringList& classes,
                             QObject* service,
                             const Dictionary& properties)
{
  if (service == 0)
  {
    throw InvalidArgumentException("Can't register 0 as a service");
  }

  // Check if service implements claimed classes and that they exist.
  for (QStringListIterator i(classes); i.hasNext();)
  {
    QString cls = i.next();
    if (cls.isEmpty())
    {
      throw InvalidArgumentException("Can't register as null class");
    }

    if (!(qobject_cast<ServiceFactory*>(service)))
    {
      if (!checkServiceClass(service, cls))
      {
        QString msg = QString("Service class %1 is not an instance of %2. Maybe you forgot the Q_INTERFACES macro in the service class.")
            .arg(service->metaObject()->className()).arg(cls);
        throw InvalidArgumentException(msg);
      }
    }
  }

  IServiceRegistration res(plugin, service,
                             createServiceProperties(properties, classes));
  {
    QMutexLocker lock(&mutex);
    services.insert(res, classes);
    for (QStringListIterator i(classes); i.hasNext(); )
    {
      QString currClass = i.next();
      QList<IServiceRegistration>& s = classServices[currClass];
      QList<IServiceRegistration>::iterator ip =
          std::lower_bound(s.begin(), s.end(), res, ServiceRegistrationComparator());
      s.insert(ip, res);
    }
  }

  IServiceReference r = res.getServiceReference();
  plugin->fwCtx->listeners.serviceChanged(
      plugin->fwCtx->listeners.getMatchingServiceSlots(r),
      ServiceEvent(ServiceEvent::REGISTERED, r));
  return res;
}

//----------------------------------------------------------------------------
void Services::updateServiceRegistrationOrder(const IServiceRegistration& sr,
                                              const QStringList& classes)
{
  QMutexLocker lock(&mutex);
  for (QStringListIterator i(classes); i.hasNext(); )
  {
    QList<IServiceRegistration>& s = classServices[i.next()];
    s.removeAll(sr);
    s.insert(std::lower_bound(s.begin(), s.end(), sr, ServiceRegistrationComparator()), sr);
  }
}

//----------------------------------------------------------------------------
bool Services::checkServiceClass(QObject* service, const QString& cls) const
{
  return service->inherits(cls.toLatin1());
}

//----------------------------------------------------------------------------
QList<IServiceRegistration> Services::get(const QString& clazz) const
{
  QMutexLocker lock(&mutex);
  return classServices.value(clazz);
}

//----------------------------------------------------------------------------
IServiceReference Services::get(BundlePrivate* plugin, const QString& clazz) const
{
  QMutexLocker lock(&mutex);
  try {
    QList<IServiceReference> srs = get_unlocked(clazz, QString(), plugin);
    if (framework->debug.service_reference)
    {
      qDebug() << "get service ref" << clazz << "for plugin"
               << plugin->location << " = " << srs.size() << "refs";
    }
    if (!srs.isEmpty()) {
      return srs.front();
    }
  }
  catch (const InvalidArgumentException& )
  { }

  return IServiceReference();
}

//----------------------------------------------------------------------------
QList<IServiceReference> Services::get(const QString& clazz, const QString& filter,
                                            BundlePrivate* plugin) const
{
  QMutexLocker lock(&mutex);
  return get_unlocked(clazz, filter, plugin);
}

//----------------------------------------------------------------------------
QList<IServiceReference> Services::get_unlocked(const QString& clazz, const QString& filter,
                                                     BundlePrivate* plugin) const
{
  Q_UNUSED(plugin)

  QListIterator<IServiceRegistration>* s = 0;
  QList<IServiceRegistration> v;
  LDAPExpr ldap;
  if (clazz.isEmpty())
  {
    if (!filter.isEmpty())
    {
      ldap = LDAPExpr(filter);
      QSet<QString> matched;
      if (ldap.getMatchedObjectClasses(matched))
      {
        v.clear();
        foreach (QString className, matched)
        {
          const QList<IServiceRegistration>& cl = classServices[className];
          v += cl;
        }
        if (!v.isEmpty())
        {
          s = new QListIterator<IServiceRegistration>(v);
        }
        else
        {
          return QList<IServiceReference>();
        }
      }
      else
      {
        s = new QListIterator<IServiceRegistration>(services.keys());
      }
    }
    else
    {
      s = new QListIterator<IServiceRegistration>(services.keys());
    }
  }
  else
  {
    QList<IServiceRegistration> v = classServices.value(clazz);
    if (!v.isEmpty())
    {
      s = new QListIterator<IServiceRegistration>(v);
    }
    else
    {
      return QList<IServiceReference>();
    }
    if (!filter.isEmpty())
    {
      ldap = LDAPExpr(filter);
    }
  }

  QList<IServiceReference> res;
  while (s->hasNext())
  {
    IServiceRegistration sr = s->next();
    IServiceReference sri = sr.getServiceReference();

    if (filter.isEmpty() || ldap.evaluate(sr.d_func()->properties, false))
    {
      res.push_back(sri);
    }
  }

  delete s;

  return res;
}

//----------------------------------------------------------------------------
void Services::removeServiceRegistration(const IServiceRegistration& sr)
{
  QMutexLocker lock(&mutex);

  QStringList classes = sr.d_func()->properties.value(BundleConstants::OBJECTCLASS).toStringList();
  services.remove(sr);
  for (QStringListIterator i(classes); i.hasNext(); )
  {
    QString currClass = i.next();
    QList<IServiceRegistration>& s = classServices[currClass];
    if (s.size() > 1)
    {
      s.removeAll(sr);
    }
    else
    {
      classServices.remove(currClass);
    }
  }
}

//----------------------------------------------------------------------------
QList<IServiceRegistration> Services::getRegisteredByPlugin(BundlePrivate* p) const
{
  QMutexLocker lock(&mutex);

  QList<IServiceRegistration> res;
  for (QHashIterator<IServiceRegistration, QStringList> i(services); i.hasNext(); )
  {
    IServiceRegistration sr = i.next().key();
    if (sr.d_func()->plugin == p)
    {
      res.push_back(sr);
    }
  }
  return res;
}

//----------------------------------------------------------------------------
QList<IServiceRegistration> Services::getUsedByPlugin(QSharedPointer<IBundle> p) const
{
  QMutexLocker lock(&mutex);

  QList<IServiceRegistration> res;
  for (QHashIterator<IServiceRegistration, QStringList> i(services); i.hasNext(); )
  {
    IServiceRegistration sr = i.next().key();
    if (sr.d_func()->isUsedByPlugin(p))
    {
      res.push_back(sr);
    }
  }
  return res;
}

